package com.gu.controller;

import com.gu.VO.ServerResponse;
import com.gu.VO.WangEditorVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @ProjectName: apartment-management-center
 * @Package: com.gu.controller
 * @ClassName: ImageUploadController
 * @Author: gusongliao
 * @Description: 图片上传控制器
 * @createDate 2021/02/25 11:11
 */
@Controller
@RequestMapping("/file")
public class ImageUploadController {

    private static final String FILE_PREFIX = "F:\\apartmentImage\\";
    private static final String SERVER_PREFIX = "http://localhost:8888/";

    @PostMapping("/upload")
    @ResponseBody
    public ServerResponse upload(MultipartFile[] file) throws IOException {

        System.out.println("upload");
        if (file == null || file.length == 0){
            return ServerResponse.error(400,"无文件信息");
        }
        List<String> pathList = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            String name = UUID.randomUUID().toString();
            File imgFile = new File(FILE_PREFIX + name + getSuffix(multipartFile));
            multipartFile.transferTo(imgFile);
            pathList.add(SERVER_PREFIX + name + getSuffix(multipartFile));
        }
        return ServerResponse.success(pathList);
    }

    public String getSuffix(MultipartFile multipartFile){
        String fileSuffixName = multipartFile.getOriginalFilename();
        String fileSuffix = fileSuffixName.substring(fileSuffixName.lastIndexOf("."));
        return fileSuffix;
    }


    @PostMapping("/wangUpload")
    @ResponseBody
    public WangEditorVO wangUpload(MultipartFile[] file) throws IOException {

        System.out.println("wang");

        ServerResponse wangResult = upload(file);

        System.out.println(wangResult.getCode());
        System.out.println(wangResult.getData());

//        if (wangResult.getCode() != 0){
//            return WangEditorVO.error(9,"文件上传失败");
//        }

        return WangEditorVO.success(wangResult.getData());
    }



}
